package com.logic.landseaserver.service.impl;


import java.util.Date;

import com.logic.system.service.IConfigurationService;
import com.logic.system.service.impl.ConfigurationService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.domain.Code;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.enums.BTypeEnum;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.token.impl.WechatBroAccessTokenSerivce;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.HttpRequestClient;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.domain.RealBill;
import com.logic.landseaserver.persistence.read.BillReadMapper;
import com.logic.landseaserver.persistence.read.ContractReadMapper;
import com.logic.landseaserver.persistence.read.CustomerReadMapper;
import com.logic.landseaserver.persistence.read.RealBillReadMapper;
import com.logic.landseaserver.service.IScheduleService;
import com.logic.landseaserver.service.ISendMsgService;
import com.logic.landseaserver.ws.dto.BillDTO;
import com.logic.landseaserver.ws.dto.ContractDTO;
import com.logic.landseaserver.ws.dto.CustomerDTO;
import com.logic.landseaserver.ws.dto.PayRechargeDTO;
import com.logic.system.service.ICodeService;


/**
 *
 * 项目名称：system-server</br>
 * 类名称：SendMsgServiceImpl</br>
 * 类描述：</br>
 * 创建人：tony</br>
 * 创建时间：2017年7月17日 下午3:29:43</br>
 * @version 1.0
 *
 */
@Service
public class SendMsgServiceImpl implements ISendMsgService {

	private String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	private static final Logger logger = LoggerFactory.getLogger(SendMsgServiceImpl.class);
	
	@Autowired
	private WechatBroAccessTokenSerivce wechatBroAccessTokenSerivce;

    @Autowired
    private CustomerReadMapper customerReadMapper;
    
    @Autowired
    private ContractReadMapper contractReadMapper;
    
    @Autowired
    private SendMsgConfiguration sendMsgConfiguration;
	@Autowired
	private BillReadMapper billReadMapper;
	@Autowired
	private RealBillReadMapper realBillReadMapper;
	@Autowired
	private ICodeService codeService;
	@Autowired
	private IScheduleService iScheduleService;
	@Autowired
	private IConfigurationService configurationService;
    
    /**
     * 
     * [描述]：</br>
     *
     * @param contractId
     * @return
     *
     */
	@Override
	public String sendMessage(Integer contractId, String billType, Integer billId){
		//生成环境只有一台服务器负责发送短信，其余平台不发送短信 -----Modify By Junny
		boolean cuteFlag = iScheduleService.sendMsgFlag();
		if (cuteFlag) {
			try{
				ContractDTO contract = contractReadMapper.queryContractDetail(contractId);
				if(contract==null){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.CONTRACT_ISNULL.getDesc());
					return -1+"";
				}
				Integer userId = contract.getUserId();
				if(userId == null){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.CONTRACT_USERID_ISNULL.getDesc());
					return -1+"";
				}
				String phone = contract.getCellphone();
				if(StringUtils.isEmpty(phone)){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.CONTRACT_OFFLINE_CREATE_CELLPHONE_ISNULL.getDesc());
					return -1+"";
				}
				String name = contract.getCertificatesName();
				if(StringUtils.isEmpty(name)){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.CONTRACT_OFFLINE_CREATE_NAME_ISNULL.getDesc());
					return -1+"";
				}
				String gender = contract.getGender();
				if(StringUtils.isNotEmpty(gender)){
					Code code = codeService.getCode(gender);
					if (code != null) {
						//gender = code.getCodeDescTr(); 注释掉短信中的女士或先生
						gender = "";
					}
				}
				CustomerDTO customer = customerReadMapper.getCustomersByUserId(userId);
				if(customer==null){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.WECHAT_BRO_CUSTOMER_NULL.getDesc());
					return -1+"";
				}
				//账单信息
				BillDTO sendBill = null;
				//实时账单
				Double billAmount = 0.0;
				// 先发送短信
				String nowMonth = DateUtil.getInstence().convertYM(new Date());
				String billName ="";
				//月结 BT1  实时BT2
				if(BTypeEnum._BT2.getCode().equals(billType)){
					billName =nowMonth+ "期实时";
					RealBill realBill = realBillReadMapper.selectByPrimaryKey(billId);
					if(realBill!=null){
						billAmount = realBill.getBillPrice();
					}
				}else{
					sendBill = billReadMapper.selectByPrimaryKey(billId);
					if(sendBill!=null){
						nowMonth = sendBill.getBillMonth();
						billName =sendBill.getBillMonth()+"期月结";
						billAmount = sendBill.getReceivableMoney();
					}else{
						billName =nowMonth+"期月结";
					}
				}
				String msg = " {'bill_name':'"+billName+"'}";
				//String msg = " {'name':'"+name+gender+"','bill_name':'"+billName+"'}";
				String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
				SMSUtil.sendSms(sendMsgConfiguration.getFirstBillCreateCode(), phone, msg,signName);
				// 再推送微信
				String openId = customer.getOpenId();
				if(StringUtils.isEmpty(openId)){
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.WECHATBRO_OPENID_NULL.getDesc());
				}
				String accesstoken;
				try
				{
					accesstoken = wechatBroAccessTokenSerivce.getAccessToken();
					logger.info("SendMsgServiceImpl | sendMessage accesstoken is :" + accesstoken);
				}
				catch (LandseaException e)
				{
					logger.info("SendMsgServiceImpl | sendMessage" + LandseaErrorMessageEnum.WECHAT_BRO_ACCESSTOKEN_ERROR.getDesc());
					return -1+"";
				}
				String sendMSGurl = sendMsgUrl.replace("ACCESS_TOKEN", accesstoken);
				String billTerm = "";
				if(nowMonth.length()==6){
					billTerm  = nowMonth.substring(0,4)+"年"+nowMonth.substring(4,6)+"月";
				}else{
					billTerm = nowMonth;
				}
				String touser = openId;
				WechatBroAccessTokenSerivce instance = WechatBroAccessTokenSerivce.getInstance();
				String template_id = instance.getTemplateId();//模板id
				// http://m.beta.langshiyu.com/unpaid.html?id=618&billType=_BT1
				StringBuffer urlPath = new StringBuffer();
				urlPath.append(instance.getTurnUrl()); // //跳转url
				urlPath.append("id="+billId);
				urlPath.append("&billType="+billType);
				String dataFormate = "{"+
						"\"touser\":\""+touser+"\","+
						"\"template_id\":\""+template_id+"\","+
						"\"url\":\""+urlPath.toString()+"\",  "+
						"\"data\":{"+
						"\"first\": {"+
						"\"value\":\"尊敬的租户您好！\","+
						"\"color\":\"#4F4F4F\""+
						"},"+
						"\"keyword1\": {"+
						"\"value\":\""+name+"\","+
						"\"color\":\"#4F4F4F\""+
						"},"+
						"\"keyword2\": {"+
						"\"value\":\""+billTerm+"\","+
						"\"color\":\"#4F4F4F\""+
						"},"+
						"\"keyword3\": {"+
						"\"value\":\""+billAmount+"元\","+
						"\"color\":\"#4F4F4F\""+
						"},"+
						"\"remark\": {"+
						"\"value\":\"请点击查看账单详请。\","+
						"\"color\":\"#4F4F4F\""+
						"}"+
						"}"+
						"}";
				logger.info("SendMsgServiceImpl | sendMessage 报文" + dataFormate);
				String result = HttpRequestClient.postHttpsRequest(sendMSGurl, dataFormate);
				logger.info("SendMsgServiceImpl | sendMessage result" + result);
				return 0+"";
			}catch(Exception e){
				logger.info("SendMsgServiceImpl | sendMessage error" + e);
				return -1+"";
			}
		}else{
			logger.info("SendMsgServiceImpl | Other evr not send msg");
			return 0+"";
		}
	}

	@Override
	public boolean sendTradeWechatMsg(String msgContent) {
		try{
			String accesstoken;
			try{
				accesstoken = wechatBroAccessTokenSerivce.getAccessToken();
				logger.info("sendTradeWechatMsg accesstoken is :" + accesstoken);
			}catch (LandseaException e){
				logger.info("sendTradeWechatMsg" + LandseaErrorMessageEnum.WECHAT_BRO_ACCESSTOKEN_ERROR.getDesc());
				return false;
			}
			String sendMSGurl = sendMsgUrl.replace("ACCESS_TOKEN", accesstoken);
			logger.info("sendTradeWechatMsg content is " + msgContent);
			String result = HttpRequestClient.postHttpsRequest(sendMSGurl, msgContent);
			logger.info("sendTradeWechatMsg result" + result);
			return true;
		}catch (Exception e){
			logger.error("sendWechatMsg Error:"+e.getMessage());
			return false;
		}
	}

	@Override
	public String formatTradeWechatMsg(Object object) {
		PayRechargeDTO rechargeDTO = (PayRechargeDTO)object;
		if(rechargeDTO.getUserId()==null||rechargeDTO.getRoomId()==null){
			logger.info(" formatTradeWechatMsg object is null");
			return null;
		}
		CustomerDTO customer = customerReadMapper.getCustomersByUserId(rechargeDTO.getUserId());
		if(customer==null){
			logger.info("SendMsgServiceImpl | formatTradeWechatMsg" + LandseaErrorMessageEnum.WECHAT_BRO_CUSTOMER_NULL.getDesc());
			return null;
		}
		String openId = customer.getOpenId();
		if(StringUtils.isEmpty(openId)){
			logger.info("SendMsgServiceImpl | formatTradeWechatMsg" + LandseaErrorMessageEnum.WECHATBRO_OPENID_NULL.getDesc());
			return null;
		}
		WechatBroAccessTokenSerivce instance = WechatBroAccessTokenSerivce.getInstance();
		String templateId = instance.getTradeTemplateId();//模板id

		String tradeAmtStr = "";
        if (rechargeDTO.getTradeAmount() >= 0.0){
            tradeAmtStr = "+" + rechargeDTO.getTradeAmount();
        }else{
            tradeAmtStr = String.valueOf(rechargeDTO.getTradeAmount());
        }
		StringBuffer urlPath = new StringBuffer();
		urlPath.append(instance.getTradeTurnUrl()); // //跳转url
		urlPath.append("&roomId="+rechargeDTO.getRoomId());
		urlPath.append("&userId="+rechargeDTO.getUserId());
		String dataFormate = "{"+
				"\"touser\":\""+openId+"\","+
				"\"template_id\":\""+templateId+"\","+
				"\"url\":\""+urlPath.toString()+"\",  "+
				"\"data\":{"+
				"\"first\": {"+
				"\"value\":\"亲爱的诗友，您的账户余额发生了变动！\","+
				"\"color\":\"#4F4F4F\""+
				"},"+
				"\"keyword1\": {"+
				"\"value\":\""+tradeAmtStr+"元\","+
				"\"color\":\"#4F4F4F\""+
				"},"+
				"\"keyword2\": {"+
				"\"value\":\""+DateUtil.getInstence().convertYMDHM(rechargeDTO.getTradeDate())+"\","+
				"\"color\":\"#4F4F4F\""+
				"},"+
				"\"keyword3\": {"+
				"\"value\":\""+rechargeDTO.getAccountAmount()+"元\","+
				"\"color\":\"#4F4F4F\""+
				"},"+
				"\"remark\": {"+
				"\"value\":\"点击查看您的账户明细，如有疑问请询问客服(400-8282-661)。\","+
				"\"color\":\"#4F4F4F\""+
				"}"+
				"}"+
				"}";
		return dataFormate;
	}


}
